<template>
  <div class="app-container">
    <el-card class="order-detail-card">
      <!-- 订单基本信息 -->
      <div class="order-info-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ orderDetail.orderId }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单来源：</span>
              <span class="value">{{ orderDetail.orderSource }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单状态：</span>
              <span class="value status-tag">{{ orderDetail.orderStatus }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ parseTime(orderDetail.createTime) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">发票信息：</span>
              <span class="value">{{ orderDetail.invoiceInfo || '暂无发票信息' }}</span>
            </div>
            <div class="info-item">
              <span class="label">收货信息：</span>
              <span class="value">{{ getFullAddress() }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ orderDetail.paymentMethod || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">买家留言：</span>
              <span class="value">{{ orderDetail.buyerNote || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">配送方式：</span>
              <span class="value">{{ orderDetail.deliveryMethod }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 商品详情表格 -->
      <div class="product-section">
        <h3>商品详情</h3>
        <el-table :data="orderDetail.orderProductList || []" border style="width: 100%">
          <el-table-column label="商品" width="300">
            <template #default="scope">
              <div class="product-info">
                <div class="product-image">
                  <el-image 
                    :src="scope.row.productImage || '/placeholder.png'" 
                    fit="cover"
                    style="width: 60px; height: 60px;"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="product-details">
                  <div class="product-name">{{ scope.row.productName }}</div>
                  <div class="product-spec">{{ scope.row.spec }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="优惠" width="200">
            <template #default="scope">
              <span>{{ scope.row.discount || '暂无未参与任何促销' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120" align="center">
            <template #default="scope">
              <span class="price">¥{{ scope.row.unitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100" align="center">
            <template #default="scope">
              <span>{{ scope.row.quantity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退款数量" width="100" align="center">
            <template #default="scope">
              <span>{{ scope.row.refundQuantity || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120" align="center">
            <template #default="scope">
              <span class="price">¥{{ scope.row.subtotal }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 订单汇总 -->
      <div class="order-summary">
        <el-row :gutter="20">
          <el-col :span="12" :offset="12">
            <div class="summary-item">
              <span class="label">商品总额：</span>
              <span class="value">¥{{ orderDetail.orderAmount }}</span>
            </div>
            <div class="summary-item">
              <span class="label">运费：</span>
              <span class="value">¥{{ orderDetail.shippingFee || '0.00' }}</span>
            </div>
            <div class="summary-item total">
              <span class="label">应付金额：</span>
              <span class="value total-amount">¥{{ getTotalAmount() }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 新增：打印发货单按钮 -->
      <div style="text-align:right;margin-bottom:20px;">
        <el-button type="primary" @click="showPrintDialog = true">打印发货单</el-button>
      </div>
    </el-card>

    <!-- 打印发货单弹窗 -->
    <el-dialog v-model="showPrintDialog" title="打印发货单" width="600px" :close-on-click-modal="false">
      <div ref="printArea" class="print-area">
        <div style="margin-bottom: 16px;">
          <span>收件人：{{ orderDetail.consigneeName }}</span>
          <span style="float:right;">手机号：{{ orderDetail.consigneePhone }}</span>
        </div>
        <div style="margin-bottom: 16px;">收货地址：{{ orderDetail.consigneeAddress }}</div>
        <div style="margin-bottom: 8px;">商品信息</div>
        <div v-for="item in orderDetail.orderProductList || []" :key="item.id" style="margin-bottom: 8px;">
          <div style="display:flex;justify-content:space-between;align-items:center;">
            <div>
              {{ item.productName }}
              <span style="margin-left:8px;">{{ item.quantity ? '数量：' + item.quantity : '' }}</span>
            </div>
          </div>
          <div style="color:#888;font-size:13px;">{{ item.spec }}</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showPrintDialog = false">关闭</el-button>
        <el-button type="primary" @click="handlePrint">打印发货单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderDetail">
import { getOrder } from "@/api/orders/order"
import { useRoute } from "vue-router"
import { Picture } from '@element-plus/icons-vue'
import { ref, onMounted, watch, getCurrentInstance } from 'vue'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

const route = useRoute()
const { proxy } = getCurrentInstance()

const orderDetail = ref({})
const showPrintDialog = ref(false)
const printArea = ref(null)

// 获取订单详情
async function fetchOrderDetail() {
  try {
    const orderId = route.params.orderId
    if (!orderId) {
      proxy.$modal.msgError("订单ID不能为空")
      return
    }
    const response = await getOrder(orderId)
    orderDetail.value = response.data
  } catch (error) {
    proxy.$modal.msgError("获取订单详情失败")
  }
}

function handlePrint() {
  const printDom = printArea.value
  html2canvas(printDom, { scale: 2 }).then(canvas => {
    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF('p', 'mm', 'a4')
    const pageWidth = pdf.internal.pageSize.getWidth()
    const pageHeight = pdf.internal.pageSize.getHeight()
    // 计算图片宽高，适配A4
    const imgWidth = pageWidth - 20
    const imgHeight = canvas.height * imgWidth / canvas.width
    pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight)
    pdf.save(`发货单_${orderDetail.value.orderId || ''}.pdf`)
  })
}

function getFullAddress() {
  const { consigneeName, consigneePhone, consigneeAddress } = orderDetail.value
  if (!consigneeName && !consigneePhone && !consigneeAddress) {
    return '-'
  }
  return `${consigneeName || ''} ${consigneePhone || ''} ${consigneeAddress || ''}`.trim()
}

function getTotalAmount() {
  const orderAmount = parseFloat(orderDetail.value.orderAmount) || 0
  const shippingFee = parseFloat(orderDetail.value.shippingFee) || 0
  return (orderAmount + shippingFee).toFixed(2)
}

watch(() => route.params.orderId, (newId) => {
  if (newId) {
    fetchOrderDetail()
  }
})

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-card {
  margin: 20px;
}

.order-info-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.value {
  color: #303133;
  flex: 1;
}

.status-tag {
  color: #ff6600;
  font-weight: 500;
}

.product-section {
  margin-bottom: 30px;
}

.product-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  margin-right: 15px;
}

.image-placeholder {
  width: 60px;
  height: 60px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 20px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.product-spec {
  color: #909399;
  font-size: 12px;
}

.price {
  color: #ff6600;
  font-weight: 500;
}

.order-summary {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  align-items: center;
}

.summary-item.total {
  border-top: 1px solid #dcdfe6;
  padding-top: 10px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: 500;
}

.total-amount {
  color: #ff6600;
  font-size: 18px;
  font-weight: bold;
}

.print-area {
  padding: 10px 0 0 0;
  font-size: 16px;
  color: #222;
}
</style>
